package org.zjvis.datascience.common.util;

import com.alibaba.fastjson.JSONObject;
import com.google.common.base.Joiner;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import org.springframework.util.StringUtils;

public class ModelUtil {
    /**
     * 转义正则特殊字符
     *
     * @param keyword
     * @return
     */
    public static String escapeExprSpecialWord(String keyword) {
        if (!StringUtils.isEmpty(keyword)) {
            keyword = keyword.replace("\\", "").replace("\'", "\\\'");
            String[] fbsArr = {"$", "(", ")", "*", "+", ".", "^", "{", "}", "|", "?", "[", "]"};
            for (String key : fbsArr) {
                if (keyword.contains(key)) {
                    keyword = keyword.replace(key, "\\\\" + key);
                }
            }
        }
        return keyword;
    }

    public static JSONObject prepareQuery(JSONObject params) {
        if (StringUtils.isEmpty(params.getString("orderKey"))) {
            params.put("orderKey", "star");
            if (StringUtils.isEmpty(params.getString("order"))) {
                params.put("order", "desc");
            }
        }

        String whereSql = "top_version=1";
        if (!StringUtils.isEmpty(params.getString("whereValue"))) {
            String key = "concat_ws(keyword, owner, name)";
            List<String> values = Arrays.asList(params.getString("whereValue").split(",|，"));
            if (values.size() > 0){
                List<String> newValues = new ArrayList<>();
                for (String value: values){
                    value = escapeExprSpecialWord(value);
                    if (!StringUtils.isEmpty(value)){
                        newValues.add(value);
                    }
                }
                if (newValues.size() > 0) {
                    whereSql = String.format("%s regexp('%s') and top_version=1", key,
                        Joiner.on("|").join(newValues));
                } else {
                    whereSql = "id=-1";
                }
            }
        }
        if (!StringUtils.isEmpty(params.getString("type"))) {
            whereSql += " and type=" + params.getString("type");
        }
        if (!StringUtils.isEmpty(params.getString("field"))) {
            String[] fields = params.getString("field").split(",|，");
            List<String> fieldSqls = new ArrayList<>();
            for (String field : fields) {
                fieldSqls.add(String.format("instr(field, '%s')", field));
            }
            whereSql += String.format(" and (%s)", Joiner.on(" or ").join(fieldSqls));
        }
        if (!StringUtils.isEmpty(params.getString("status"))) {
            whereSql += " and status=" + params.getString("status");
        }

        //add user_id and group by model_id, user_id
        whereSql += String.format(
            " and user_id =%s and id in (select min(id) from model_local group by model_id, user_id)",
            params.getLong("userId"));
        params.put("where", whereSql);

        Long pageIndex = params.getLong("pageIndex");
        Long pageSize = params.getLong("pageSize");
        Long offset = (pageIndex - 1) * pageSize;
        String pageSql = String.format("LIMIT %s OFFSET %s", pageSize, offset);
        params.put("pageSql", pageSql);
        return params;
    }
}
